﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtensionLoader;
using WebDAVSharp;
using WebDAVSharp.NHibernateStorage;
using ExtensionLoader.Config;

namespace InventoryServer.Extensions.WebDAV.PropertyStorage.NHibernate
{
    public class NHibernateStorage : IExtension<InventoryServer>, IPropertyProvider
    {
        protected NHibernateIWebDAVResource storageModule;
        private string name = "NHibernateStorage";
        private string connectionString;

        #region IPropertyProvider Members

        public bool Save(IWebDAVResource resource)
        {
            return storageModule.SaveResource(resource);
        }

        public IWebDAVResource Load(string path)
        {
            return storageModule.GetResource(path);
        }

        #endregion

        #region IExtension<InventoryServer> Members

        InventoryServer m_server = null;

        public bool Start(InventoryServer owner)
        {
            bool enableThis = false;
            
            #region Config Loading

            try
            {
                IConfig webdavconfig = owner.ConfigFile.Configs["WebDAV"];
                if (webdavconfig != null)
                {
                    connectionString = webdavconfig.GetString("ConnectionString", String.Empty);
                    if (connectionString != String.Empty)
                    {
                        enableThis = true;
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }

            #endregion Config Loading

            if (enableThis)
            {
                m_server = owner;
                storageModule = new NHibernateIWebDAVResource();
                storageModule.Initialise(connectionString);
            }

            return true;
        }

        public void Stop()
        {
            m_server = null;
            storageModule.Dispose();
        }

        #endregion
    }
}
